package com.wlw.web;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.wlw.entity.City;
import com.wlw.entity.Province;
import com.wlw.entity.QA;
import com.wlw.entity.Scenery;
import com.wlw.entity.TravalNote;
import com.wlw.entity.User;
import com.wlw.service.CityService;
import com.wlw.service.GonglueService;
import com.wlw.service.ProvinceService;
import com.wlw.service.QAService;
import com.wlw.service.QAreplyService;
import com.wlw.service.SceneryService;
import com.wlw.service.TravalNoteService;
import com.wlw.service.UserService;
import edu.xjsoft.base.orm.support.Page;
import edu.xjsoft.base.orm.support.PropertyFilter;
import edu.xjsoft.base.util.CipherUtil;

@Controller
@RequestMapping("/user/*")
public class UserAction {
	@Autowired
	private UserService userService;
	@Autowired
	private GonglueService gonglueService;
	@Autowired
	private CityService cityService;
	@Autowired
	private SceneryService sceneryService;
	@Autowired
	private ProvinceService provinceService;
	@Autowired
	private TravalNoteService travalNoteService;
	@Autowired
	private QAService qaService;
	CipherUtil cipher = new CipherUtil();
	@RequestMapping("register")
	public String register(User user){
		String pwd = user.getPwd();
		user.setPwd(cipher.generatePassword(pwd));
		userService.saveOrUpdate(user);
		return "foreground/index";
	}
	
	@RequestMapping("login")
	public String login(HttpServletRequest req){
		CipherUtil cipher = new CipherUtil();
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		System.out.println("已经加载至此：login！");
		PropertyFilter filters = new PropertyFilter("uname", uname);
		List<User> users = userService.search(filters);
		if (users.size()==0) {
			return "redirect:../foreground/index.jsp";
		}
		if (cipher.validatePassword(users.get(0).getPwd(), pwd)) {
			req.getSession().setAttribute("user", users.get(0));
		}else {
			return "redirect:../foreground/index.jsp";
		}
		return "redirect:../foreground/index.jsp";
	}
	@RequestMapping("logout")
	public String logout(HttpServletRequest req){
		req.getSession().removeAttribute("user");
		req.getSession().invalidate();
		return "redirect:../foreground/index.jsp";
	}
	@RequestMapping("myInfo")
	public String myInfo(HttpServletRequest req,Model model){
		//获得个人资料
		User u = (User) req.getSession().getAttribute("user");
		model.addAttribute("u", u);
		//获得我的足迹：
		List<TravalNote> getUserTravalNotes = travalNoteService.getUserTravalNotes(req);
		model.addAttribute("getUserTravalNotes", getUserTravalNotes);
		return "foreground/myInfo";
		//我的游记
	}
	/**
	 * @param myfile 首页登陆（传送数据）
	 * @param req 
	 * @param model 
	 * @return 周边推荐、热门推荐、国内旅游推荐、境外旅游推荐。
	 * @throws UnsupportedEncodingException 
	 * @throws IOException
	 */
	@RequestMapping("index")
	public String index(HttpServletRequest req,Model model) throws UnsupportedEncodingException{
		//目的地导航：
		//国内
		List<Province> homeProvinces = provinceService.homeProvince();
		model.addAttribute("homeProvinces", homeProvinces);
//		List<City> allHomeCities = cityService.homeCityClass();
//		model.addAttribute("allHomeCities", allHomeCities);
//		//国外
//		List<City> allForeignCities = cityService.foreignCityClass();
//		model.addAttribute("allForeignCities", allForeignCities);
		//热门推荐攻略：(根据城市攻略的下载量)
		List<City> cities = cityService.hotCities();
		model.addAttribute("cities", cities);
		//热门国内推荐：（根据国内景点的点赞数进行排序）
		List<Scenery> homeSceneries = sceneryService.homeHotScenery();
		model.addAttribute("homeSceneries", homeSceneries);
		//热门境外推荐：
		List<Scenery> foreignSceneries = sceneryService.foreignHotScenery();
		model.addAttribute("foreignSceneries", foreignSceneries);
		//周边推荐：
		String province = req.getParameter("province");
		String city = req.getParameter("city");
		//解决乱码问题：
		//通过两次encodeURI()加密 再通过一次decode解密。
		if (province!=null&&city!=null) {
			province = java.net.URLDecoder.decode(province , "UTF-8");
			city = java.net.URLDecoder.decode(city,"UTF-8");
			System.out.println("省份：：：："+province);
			System.out.println("城市：：：："+city);
			PropertyFilter filters = new PropertyFilter("name",city);
			List<City> cities2 = cityService.search(filters);
			PropertyFilter filtersp = new PropertyFilter("name",province);
			List<Province> provinces = provinceService.search(filtersp);
			if (cities2.size()!=0) {
				List<Scenery> localSceneries = sceneryService.localSceneries(city);
				model.addAttribute("localSceneries", localSceneries);
			}
			if (provinces.size()!=0) {
				List<City> localCities = cityService.localCities(province);
				model.addAttribute("localCities", localCities);
			}
		}				
		return "foreground/index";
	}
	@RequestMapping("search")
	public String search(HttpServletRequest req,Model model) throws UnsupportedEncodingException{
		int type = Integer.parseInt(req.getParameter("search_type"));
		String search = req.getParameter("search");
		//乱码问题：
		System.out.println("你搜索的是："+type+":"+search);
		search = java.net.URLDecoder.decode(search,"UTF-8");
		//景点
		if (type==1) {
			List<Scenery> sceneries = sceneryService.searchScenery(search);
			model.addAttribute("sceneries", sceneries);
			return "foreground/sceneryDetail";
		}
		//城市
		if (type==2) {
			List<City> cities = cityService.searchCities(search);
			model.addAttribute("cities", cities);
			return "foreground/cityDetail";
		}
		//问答
		if (type==3) {
			List<QA> qas = qaService.searchQA(search);
			model.addAttribute("qas", qas);
			return "foreground/ListQaReply";
		}
		return "";
	}
	
	@RequestMapping("modMyInfo")
	public String modMyInfo(@RequestParam MultipartFile myfile,HttpServletRequest req,Model model)throws IOException {
		System.out.println("加载到修改模块：modMyInfo！");
		String endType = "";
		int id = Integer.parseInt(req.getParameter("id"));
		PropertyFilter filters = new PropertyFilter("id", id);
		List<User> users = userService.search(filters);
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		pwd = cipher.generatePassword(pwd);
		String sex = req.getParameter("sex");
		String email = req.getParameter("email");
		String telPhone = req.getParameter("telPhone");
		//得到服务器的路径
		String root = req.getSession().getServletContext().getRealPath("/");
		File uploadDir = new File(root, "foreground/tourGonglue_files/headPortrait").getCanonicalFile();
		if (!uploadDir.exists() || uploadDir.isFile()) {
			uploadDir.mkdir();
		}
		if (!myfile.isEmpty()) {
			System.out.println("myfile为空！");
			File file = new File(uploadDir+"/"+users.get(0).getUname()+".jpg");
			System.out.println("QQQQQQQQQQQQQQQQQQQQQ:"+uploadDir+"/"+users.get(0).getUname()+".jpg");
			if (file.exists()) {
				boolean b = file.delete();
				System.out.println(":::::"+b);
			}
		}
		// 如果选择了上传的文件
		if (!myfile.isEmpty()) {
			String name1 = myfile.getName();
			String name2 = myfile.getOriginalFilename();
			String type = myfile.getContentType();
			long length = myfile.getSize();
			// 得到要上传文件的后缀名
			endType = name2.substring(name2.lastIndexOf("."),name2.length());
			users.get(0).setHeadPortrait("foreground/tourGonglue_files/headPortrait"+"/"+uname+endType);
			System.out.println("foreground/tourGonglue_files/headPortrait"+"/"+uname+endType);
			System.out.println(name1);
			System.out.println(name2);
			System.out.println(type);
			System.out.println(endType);
			System.out.println("文件大小：" + length + " 字节");
			// 处理小文件：
			// myfile.transferTo(new File(uploadDir, name2));
			// 处理大文件：
			InputStream is = myfile.getInputStream();
			FileOutputStream fos = new FileOutputStream(new File(uploadDir,
					uname + endType));
			System.out.println(uname+endType);
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = is.read(b)) > 0) {
				fos.write(b, 0, len);
			}
			fos.flush();
			fos.close();
			is.close();
		}
		users.get(0).setUname(uname);
		users.get(0).setEmail(email);
		users.get(0).setSex(sex);
		users.get(0).setTelPhone(telPhone);
		userService.saveOrUpdate(users.get(0));
		req.getSession().setAttribute("user", users.get(0));
		model.addAttribute("u", users.get(0));
		return "foreground/myInfo";
	}	
	
	
//以下是后台的操作：	
//////////////////////////////////////////////////////////////////////////////////////////
	@RequestMapping("addUser")
	public String addUser(HttpServletRequest req){
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		pwd = cipher.generatePassword(pwd);
		String sex = req.getParameter("sex");
		String email = req.getParameter("email");
		String telPhone = req.getParameter("telPhone");
		System.out.println("加载至此！user!");
		User user = new User();
		user.setUname(uname);
		user.setPwd(pwd);
		user.setSex(sex);
		user.setEmail(email);
		user.setTelPhone(telPhone);
		PropertyFilter filters = new PropertyFilter("uname", uname);
		List<User> users = userService.search(filters);
		if (users.size()==0) {
			userService.saveOrUpdate(user);
			return "background/success";
		}else {
			return "background/failure";
		}
	}
	@RequestMapping("modUser")
	public String modify(HttpServletRequest req,Model model) {
		String uname = req.getParameter("uname");
		System.out.println("加载至此！uname="+uname);
		PropertyFilter filters = new PropertyFilter("uname", uname);
		List<User> users = userService.search(filters);
		model.addAttribute("user", users);
		return "background/modUser";
	}
	@RequestMapping("modifyUser")
	public String modifyUser(HttpServletRequest req){
		int id = Integer.parseInt(req.getParameter("id"));
		PropertyFilter filters = new PropertyFilter("id", id);
		List<User> users = userService.search(filters);
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		pwd = cipher.generatePassword(pwd);
		String sex = req.getParameter("sex");
		String email = req.getParameter("email");
		String telPhone = req.getParameter("telPhone");
		System.out.println("加载至此！user!");
		users.get(0).setUname(uname);
		users.get(0).setPwd(pwd);
		users.get(0).setSex(sex);
		users.get(0).setEmail(email);
		users.get(0).setTelPhone(telPhone);
		userService.saveOrUpdate(users.get(0));
		return "background/success";
	}
	@RequestMapping("delUser")
	public String delUser(HttpServletRequest req,Model model) {
		String idStr = req.getParameter("id");
		int id = Integer.parseInt(idStr);
		System.out.println("加载至此！uname="+id);
		userService.remove(id);
		return "background/success";
	}
	@RequestMapping("multiDel")
	public String multiDel(HttpServletRequest req){
		System.out.println("已经加载至此，multi!");
		String name[] = req.getParameterValues("checkbox");
		System.out.println("SSSSSSS:");
		System.out.println("sdfsd:"+name.length);
			for (String i : name) {
				int id = Integer.parseInt(i);
				System.out.println("id:"+id);
				userService.remove(id);
			}
			return "background/successDel";
	}
	@Deprecated
	@RequestMapping
	public String list(@RequestParam(defaultValue="1") int pageNo, Model model) {
		System.out.println("已经加载到此list！");
		Page<User> page = new Page<User>(5);
		page.setPageNo(pageNo);
		userService.loadAll(page);
		model.addAttribute("page", page);
		return "background/findUser";
	}
	
	@RequestMapping("{pageNo}")
	public String list1(@PathVariable int pageNo,Model model){
		System.out.println("加载至此");
		Page<User> page = new Page<User>(5);
		page.setPageNo(pageNo);
		userService.loadAll(page);
		model.addAttribute("page",page);
		return "background/findUser";
	}
//以上是后台的操作，为止！	
//////////////////////////////////////////////////////////////////////////////////////////
}
